import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from "../views/layout/layout.vue";
import addDynamicRoutes from '../utils/addRoutes';
import { ElMessage } from 'element-plus'
import 'element-plus/es/components/message/style/css'
// router/index.ts
let dynamicAdded = false   // 只在这一份文件里用
const routes = [
    {
        path: '/',
        name: 'Layout',
        component: Layout,
        meta: { check: true },
        redirect: '/home',
        children: [],
    },
    // 例如
    {
        path: '/home',
        name: 'home',
        component: () => import('../views/shouYe/index.vue'),
        meta: { check: true }   // 补上
    },
    {
        path: '/login',
        name: 'login',
        meta: { check: false },
        component: () => import('../views/login/Login.vue')
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
});


router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('wuyetoken')

    console.log(router.getRoutes())

    console.log(to, token)
    // 1. 未登录 & 需要鉴权
    // 判断条件是默认注册到路由的页面,通过meta.check判断页面是否需要登录
    // 这里我在登录后才注册的404路由,也就是登录后不存在的页面是404,如果需求是不登录只要页面不存在就显示404,可以把下面的注册404的逻辑,放到上面静态路由里面,这样就无需登录,不存在页面直接404
    if (!token && to.meta?.check || !token && !to.name) {
        console.log('未登录')
        ElMessage.error('未登录，请先登录')
        return next({ name: 'login' })
    }

    // 2. 已登录 & 还没添加过动态路由
    if (token && !dynamicAdded) {
        dynamicAdded = true // 先置位，防止重入
        const menus = JSON.parse(localStorage.getItem('wuyemenusJSON') || '[]')
        addDynamicRoutes(router, menus)  // 批量添加路由
        // 登录后注册404路由,这个一定要放到最后
        router.addRoute({
            path: '/:pathMatch(.*)*',
            name: '404',
            component: () => import('@/views/error/NotFound.vue')
        })
        return next({ ...to, replace: true })     // 重新进入当前页
    }
    next()
})

export default router
